﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Request;
using DocumentFormat.OpenXml.Wordprocessing;
using Elastic.Clients.Elasticsearch.Snapshot;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application.Service;

/// <summary>
/// 交通实体接口
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Name = "Traffic", Order = 200)]
public class TrafficService : IDynamicApiController {

    private readonly UserManager _userManager;

    /// <summary>
    /// 数据库仓储接口
    /// </summary>
    private readonly ISqlSugarRepository<TrafficEntity> _repository;
    private HttpContext _httpContext;

    public TrafficService(UserManager userManager, 
        IHttpContextAccessor httpContext,
        SqlSugarRepository<TrafficEntity> repository) {
        _userManager = userManager;
        _repository = repository;
        _httpContext = httpContext.HttpContext;
    }


    #region 1.0 分页查询数据 +Task<SqlSugarPagedList<TrafficEntity>> GetList([FromQuery] ListTrafficInput input)
    [HttpGet]
    [AllowAnonymous]
    public async Task<SqlSugarPagedList<TrafficEntity>> GetList([FromQuery] ListTrafficInput input) {

        SqlSugarPagedList<TrafficEntity> list = await _repository.AsQueryable()
            .WhereIF(!String.IsNullOrWhiteSpace(input.Keyword), it =>   it.Title.Contains(input.Keyword) )
             .WhereIF(input.Status.HasValue, it => it.Status.Equals(input.Status)) 
             .ToPagedListAsync(input.Page, input.PageSize);

        // 查询所有交通数据
        return list;
    }
    #endregion

    #region 2.0 主键获取实体 +Task<TrafficEntity> GetById(string id) 
    [AllowAnonymous]
    [HttpGet("{id}")]
    public async Task<TrafficEntity> GetById(long? id) {
        TrafficEntity entity = await _repository.GetByIdAsync( id);
        if (entity == null) {
            throw new Exception("交通不存在");
        }

        int viewCount = entity.ViewCount ?? 0;
        _repository.AsUpdateable()
            .SetColumns(it => it.ViewCount == viewCount + 1)
            .Where(it => it.Id == entity.Id)
            .ExecuteCommand();
        return entity;
    }
    #endregion

    #region 3.0 新增实体数据 +Task Create([FromBody] TrafficRequest input) 
    [HttpPost]
    public async Task Create([FromBody] TrafficRequest input) {
        if (input == null) {
            throw Oops.Oh("请求数据不能为空");
        }
        TrafficEntity entity = input.Adapt<TrafficEntity>(); 
        entity.CreateUserId = _userManager.UserId;
        entity.CreateUserName = _userManager.Account;
        entity.LikeCount = 0;
        entity.VetoCount = 0;
        entity.ClientIp = _httpContext.GetRemoteIpAddressToIPv4();
        await _repository.Context.Insertable(entity)
            .CallEntityMethod(it => it.Creater()).ExecuteCommandAsync();
    }
    #endregion

    #region 4.0 移除主键的数据 +Task Delete(string id) 
    [HttpDelete("{id}")]
    public async Task Delete(string id) {
        if (string.IsNullOrWhiteSpace(id)) {
            throw Oops.Oh("ID不能为空");
        }
        // 查询所有交通数据
        await _repository.DeleteByIdAsync(long.Parse(id));
    }
    #endregion

    #region 5.0 修改实体数据 +Task Update([FromBody] TrafficRequest input)
    [HttpPut]
    public async Task Update([FromBody] TrafficRequest input) {
        if (input == null) {
            throw Oops.Oh("请求数据不能为空");
        }
        if (string.IsNullOrWhiteSpace(input.Id)) {
            throw Oops.Oh("ID不能为空");
        }
        TrafficEntity entity = input.Adapt<TrafficEntity>(); 
        entity.UpdateTime = DateTime.Now;
        entity.UpdateUserId = _userManager.UserId;
        // 更新交通数据 
        if (!await _repository.UpdateAsync(entity)) {
            throw Oops.Oh("更新交通数据失败");
        }

    }
    #endregion


}